<template>
  <div>
    <header class="nav">
      <div class="nav-inner">
        <a href="#/" class="brand">
          <span class="brand-badge"></span>
          <span>点点吃 Online</span>
        </a>
        <nav class="nav-links">
          <a href="#/">首页</a>
          <a href="#/orders" v-if="user">我的订单</a>
          <a href="#/cart" v-if="user">购物车</a>
          <a href="#/profile" v-if="user">个人信息</a>
          <a href="#/login" v-if="!user">登录</a>
          <a href="#/register" v-if="!user">注册</a>
          <a href="#" @click.prevent="logout" v-if="user">退出登录</a>
        </nav>
      </div>
    </header>
    <main class="container">
      <component :is="currentView" />
    </main>
  </div>
  </template>

<script>
import Home from './pages/Home.vue'
import Login from './pages/Login.vue'
import Register from './pages/Register.vue'
import Restaurant from './pages/Restaurant.vue'
import Cart from './pages/Cart.vue'
import Orders from './pages/Orders.vue'
import Profile from './pages/Profile.vue'
import OrderDetail from './pages/OrderDetail.vue'

export default {
  name: 'App',
  components: { Home, Login, Register, Restaurant, Cart, Orders, Profile, OrderDetail },
  data(){
    return {
      route: window.location.hash,
      user: null // 初始化为null，确保页面加载时显示未登录状态
    }
  },
  computed:{
    currentView(){
      const hash = this.route.replace('#','') || '/'
      if(hash.startsWith('/restaurant')) return 'Restaurant'
      if(hash.startsWith('/login')) return 'Login'
      if(hash.startsWith('/register')) return 'Register'
      if(hash.startsWith('/cart')) return 'Cart'
      if(hash.startsWith('/orders')) return 'Orders'
      if(hash.startsWith('/order/')) return 'OrderDetail'
      if(hash.startsWith('/profile')) return 'Profile'
      return 'Home'
    }
  },
  methods: {
    logout() {
      localStorage.removeItem('user')
      this.user = null
      location.hash = '#/'
      alert('已退出登录')
    },
    updateUserStatus() {
      this.user = JSON.parse(localStorage.getItem('user')||'null')
    }
  },
  created(){
    // 确保页面加载时没有特定hash的情况下显示首页
    if (!window.location.hash || window.location.hash === '#') {
      window.location.hash = '#/'
    }
    this.route = window.location.hash
    window.addEventListener('hashchange', ()=>{ this.route = window.location.hash })
    // 初始化用户状态
    this.updateUserStatus()
    // 监听storage事件，以便在其他标签页登录/退出时更新当前页面
    window.addEventListener('storage', this.updateUserStatus)
  },
  beforeUnmount() {
    window.removeEventListener('storage', this.updateUserStatus)
  }
}
</script>

<style>
a { text-decoration: none; }
</style>


